package com.toogu.mazhangmen.util;

import static com.manager.push.XMPushManager.PUSH_TYPE_XM;

import android.app.Activity;
import android.os.Message;
import android.widget.Toast;

import com.basic.G;
import com.lib.EFUN_ERROR;
import com.lib.Mps.SMCInitInfo;
import com.lib.MsgContent;
import com.lib.SDKCONST;
import com.lib.sdk.bean.StringUtils;
import com.lib.sdk.bean.alarm.AlarmInfo;
import com.manager.account.XMAccountManager;
import com.manager.device.DeviceManager;
import com.manager.device.media.MediaManager;
import com.manager.device.media.attribute.PlayerAttribute;
import com.manager.device.media.monitor.MonitorManager;
import com.manager.push.XMPushManager;
import com.toogu.mazhangmen.bean.EquipmentsBean;
import com.toogu.mazhangmen.sdk.DeviceManager2;
import com.toogu.mazhangmen.ui.view.MonitorView;
import com.utils.XUtils;

public class MonitorUtil {
    private MonitorManager monitorManager=null;
    private XMPushManager xmPushManager = null;
    private Activity activity;
    private EquipmentsBean equipmentsBean;
    private MonitorView monitorView;

    private boolean isConnected =false;

    public MonitorUtil(Activity activity, EquipmentsBean equipmentsBean, MonitorView monitorView){
        this.activity=activity;
        this.equipmentsBean=equipmentsBean;
        this.monitorView=monitorView;
        init();
    }

    private void init() {
        monitorView.setTitle(equipmentsBean.getName());
        monitorView.setConnecting();
        if (EquipmentUtil.isHelp(equipmentsBean.getCode())) monitorView.setHelp();
        DeviceManager2.getInstance().loginDev(equipmentsBean.getCode(), equipmentsBean.getUsername(), equipmentsBean.getPassword(), new DeviceManager.OnDevManagerListener() {
            @Override
            public void onSuccess(String devId, int operationType, Object result) {
                MonitorManagerInit();
                startMonitor();
            }

            @Override
            public void onFailed(String devId, int msgId, String jsonName, int errorId) {
                String errorName = "";
                if (errorId == EFUN_ERROR.EE_DVR_SDK_TIMEOUT) {
                    monitorView.setErrorMessage("连接超时...");
                    MonitorManagerInit();
                    startMonitor();
                    return;
                }
                monitorView.setErrorMessage("错误信息：" + errorId + "\n" + FunError.getErrorStr(errorId));
            }
        });
    }
    private void MonitorManagerInit(){

        monitorManager = DeviceManager2.getInstance().createMonitorPlayer(monitorView.getMonitorView(), equipmentsBean.getCode());
        monitorManager.setOnMediaManagerListener(new MediaManager.OnMediaManagerListener() {
            @Override
            public void onMediaPlayState(PlayerAttribute attribute, int state) {
                switch (state){
                    case PlayerAttribute.E_STATE_PlAY:
                        isConnected=true;
                        monitorView.setIsConnected();
                        if(EquipmentUtil.isHelp(equipmentsBean.getCode())) monitorView.setHelp();
                        return;
                    case PlayerAttribute.E_STATE_PAUSE:
                        monitorView.setErrorMessage("暂停");
                        if(EquipmentUtil.isHelp(equipmentsBean.getCode())) monitorView.setHelp();
                        return;
                }
            }
            @Override
            public void onFailed(PlayerAttribute attribute, int msgId, int errorId) {
                monitorView.setErrorMessage("错误信息："+errorId+"\n"+FunError.getErrorStr(errorId));
                if(EquipmentUtil.isHelp(equipmentsBean.getCode())) monitorView.setHelp();
            }

            @Override
            public void onShowRateAndTime(PlayerAttribute attribute, boolean isShowTime, String time, String rate) {

            }

            @Override
            public void onVideoBufferEnd(PlayerAttribute attribute, MsgContent ex) {

            }
        });
        xmPushManager = new XMPushManager(xmPushLinkResult);
        String pushToken = XUtils.getPushToken(activity);
        if (!StringUtils.isStringNULL(pushToken)) {
            SMCInitInfo info = new SMCInitInfo();
            G.SetValue(info.st_0_user, XMAccountManager.getInstance().getAccountName());
            G.SetValue(info.st_1_password, XMAccountManager.getInstance().getPassword());
            G.SetValue(info.st_2_token, pushToken);
            xmPushManager.initFunSDKPush(info,PUSH_TYPE_XM);
        }
        //订阅
        xmPushManager.linkAlarm(equipmentsBean.getCode(),0);

    }
    private XMPushManager.XMPushLinkResult xmPushLinkResult = new XMPushManager.XMPushLinkResult() {
        @Override
        public void onPushInit(int pushType, int errorId) {
            super.onPushInit(pushType, errorId);
            if (errorId >= 0) {
                System.out.println("推送初始化成功:" + pushType);
            }else {
                System.out.println("推送初始化失败:" + errorId);
            }
        }

        @Override
        public void onPushLink(int pushType, String devId, int seq, int errorId) {
            super.onPushLink(pushType, devId, seq, errorId);
            if (errorId >= 0) {
                System.out.println("推送订阅成功:" + devId);
            }else {
                System.out.println("推送订阅失败:" + devId + ":" + errorId);
            }
        }

        @Override
        public void onPushUnLink(int pushType, String devId, int seq, int errorId) {
            super.onPushUnLink(pushType, devId, seq, errorId);
            if (errorId >= 0) {
                System.out.println("取消订阅成功:" + devId);
            }else {
                System.out.println("取消订阅失败:" + devId + ":" + errorId);
            }
        }

        @Override
        public void onAlarmInfo(int pushType, String devId, Message msg, MsgContent ex) {
            super.onAlarmInfo(pushType, devId, msg, ex);
            String pushMsg = G.ToString(ex.pData);
            System.out.println("接收到报警消息:" + pushMsg);
//            parseAlarmInfo(pushMsg);
        }
    };

    private void parseAlarmInfo(String pushMsg) {
        AlarmInfo alarmInfo = new AlarmInfo();
        alarmInfo.onParse(pushMsg);
        Toast.makeText(activity,"接收到报警消息:" +
                XMPushManager.getAlarmName(activity,alarmInfo.getEvent()) + ":" +
                alarmInfo.getStartTime(),Toast.LENGTH_LONG).show();
    }


    public boolean getIsConnected(){
        return isConnected;
    }

    public void startMonitor(){
        if(monitorManager!=null) {
            monitorManager.setStreamType(SDKCONST.StreamType.Extra);//设置主副码流，Extra副码流，Main主码流
            monitorManager.setChnId(0);//设置通道ID
            monitorManager.startMonitor();
        }
    }

    public void reStartMonitor(){
        if(monitorManager!=null) {
            monitorView.setConnecting();
            monitorManager.stopPlay();
            monitorManager.startMonitor();
        }
    }

    public void stopMonitor() {
        if(monitorManager!=null) {
            isConnected = false;
            monitorManager.stopTalkByDoubleDirection();
            monitorManager.closeVoiceBySound();
            monitorManager.stopPlay();
        }
    }

    public void destroyMonitor(){
        if(monitorManager!=null) {
            isConnected = false;
            stopMonitor();
            monitorManager.destroyPlay();
            monitorManager.release();
        }
    }

    public void openVoice() {
        if(isConnected&&monitorManager!=null) {
            monitorManager.openVoiceBySound();
        }
    }
    public void closeVoice(){
        if(isConnected&&monitorManager!=null) {
            monitorManager.closeVoiceBySound();
        }
    }

    public void openTalk() {
        if(isConnected&&monitorManager!=null) {
//            monitorManager.startTalkByDoubleDirection(activity, true);
            closeVoice();
            monitorManager.startTalkByHalfDuplex(activity);

        }
    }

    public void closeTalk(){
        if(isConnected&&monitorManager!=null) {
//            monitorManager.stopTalkByDoubleDirection();
            monitorManager.stopTalkByHalfDuplex();
            monitorManager.destroyTalk();
            openVoice();
        }
    }

    public void pushAlarm(){

    }

    public void closeAlarm(){

    }

    public MonitorView getMonitorView() {
        return monitorView;
    }
}
